# eccodes - grib 1
# xarry engine ({"netcdf4", "scipy", "pydap", "h5netcdf", "pynio", "cfgrib", "zarr"}
#
from eccodes import *
import os
import eccodes
import netCDF4
import cfgrib
import xarray

print('eccodes version = ', eccodes.__version__)
# print('netCDF4 version = ', netCDF4.__version__)
# print('cfgrib  version = ', cfgrib.__version__)
# print('xarray  version = ', xarray.__version__)
# print(eccodes.codes_get_version_info())


def grib1_file(fname: str):
    """ 读取 GRIB1 文件 """
    if not os.path.exists(fname):
        print("文件不存在 - ", fname)
    else:
        ds = xarray.open_dataset(fname, engine='cfgrib')
        # ds = xarray.open_dataset(fname, engine='cfgrib', backend_kwargs={
        #     'filter_by_keys': {'typeOfLevel': 'isobaricInhPa'}})
        print(ds)

    return


#!/usr/bin/env python
# -*- coding:utf-

# 打开文件


# 读取grib1数据
# fname = r"E:\sfxData\ECMWF\ERA5\20200802.grib"
fname = r"E:\sfxData\ECMWF\eccodes_test_data\era5-levels-members.grib"
# fname = r"E:\sfxData\ECMWF\20200812\Z_NWGD_C_BEZZ_20200812050159_P_RFFC_SPCC-TMIN_202008120800_16824.GRB2"
grib1_file(fname)

# ds = xarray.open_dataset(fname, engine='cfgrib')
# ds = xarray.open_dataset(fname, engine='cfgrib', backend_kwargs={
#     'filter_by_keys': {'step': 'isobaricInhPa'}})
# print(ds)
# print()

# print(ds.dims)
# print(ds.coords)
# print(ds.data_vars)
# print(ds.attrs)
# print(ds.variables)

# print(ds.dims.keys())
# print(ds.coords.keys())
# print(ds.variables.keys())

# print()
# print(ds['unknown'])

# codes_new_from_

# def ec_read(fname: str):
#     ifile = open(fname)
#     while 1:
#         igrib = codes_grib_new_from_file(ifile)
#         if igrib is None:
#             break

#         # 从加载的message中解码/编码数据
#         date = codes_get(igrib, "dataDate")
#         levtype = codes_get(igrib, "typeOfLevel")
#         level = codes_get(igrib, "level")
#         values = codes_get_values(igrib)
#         print(date, levtype, level, values[0], values[len(values)-1])

#         # 释放
#         codes_release(igrib)

#     ifile.close()
#     return


# fr = FileReader(fname)
# print(fr.peek())
